import os
import json
import requests
from PIL import Image
import base64


def file_exists(file_path):
    return os.path.isfile(file_path)


def download_file(url, save_path):
    # 指定保存目录
    source = url
    if "." not in source or "=" in source:

        source_path = source + ".png"
    else:
        source_path = source
    save_dir = save_path

    # 创建目录（如果不存在的话）
    os.makedirs(save_dir, exist_ok=True)
    # 获取图片的文件名
    filename = os.path.join(save_dir, source_path.split('/')[-1])

    # 下载图片
    try:
        response = requests.get(source)
        response.raise_for_status()  # 检查请求是否成功

        # 将内容写入文件
        with open(filename, 'wb') as file:
            file.write(response.content)

        print(f"图片已成功下载并保存到: {filename}")

    except requests.exceptions.RequestException as e:
        print(f"下载失败: {e}")
    return filename


def getSize(path):
    # 图片文件路径
    image_path = path  # 替换为你的图片路径

    # 打开图片
    with Image.open(image_path) as img:
        # 获取尺寸
        width, height = img.size
        return width, height


def save_base64_image(data_uri, id):
    # 检查数据格式，支持 PNG、JPG 和 JPEG
    if data_uri.startswith('data:image/png;base64,'):
        image_format = 'png'
        base64_data = data_uri.split(',')[1]
    elif data_uri.startswith('data:image/jpeg;base64,'):
        image_format = 'jpeg'
        base64_data = data_uri.split(',')[1]
    elif data_uri.startswith('data:image/jpg;base64,'):
        image_format = 'jpg'
        base64_data = data_uri.split(',')[1]
    else:
        print("无效的图像数据格式")
        return

    # 解码 base64 数据
    image_data = base64.b64decode(base64_data)

    # 将解码后的数据写入文件
    output_file = id + "." + image_format
    with open(output_file, 'wb') as file:
        file.write(image_data)
    print(f"图片已保存为 {id + '.' + image_format}")


file_path = './data/test.json'

# 打开文件并读取内容
with open(file_path, 'r', encoding='utf-8') as file:
    content = json.loads(file.read())

version = content['version']
application_version = content['application_version']
size = content['size']
work_type = content['work_type']
project_name = content['project_name']
theatre = content['theatre']
bg_picture = theatre["scenes"][theatre["scenes_order"][0]]
styles_list = theatre['styles']
screens_list = theatre["scenes_order"]

ini = {
    "screen": {
    },
    "ini": {
        "version": version,
        "author": "https://shequ.codemao.cn/",
        "desc": "基于Pygame，PygameHelp，编程猫Kitten编辑器工程文件的游戏",
        "title": project_name,
        "icon": "favorite.ico",
        "w": size["width"],
        "h": size["height"],
        "fps": 60,
        "isFullSize": False,
        "color": {"r": 255, "g": 255, "b": 255}
    }}

# 屏幕初始化
for i in screens_list:
    senceId = i
    source = styles_list[theatre["scenes"][senceId]["styles"][0]]["cdn_url"]
    # 将其用requste下载到本地
    filename = download_file(source, './data/img')
    ini["screen"][senceId] = {"source": filename}

# 角色初始化
for i in theatre["groups"]:
    for j in theatre["groups"][i]["actors"]:
        # 去寻找这个角色
        o = theatre["actors"][j]
        x = o["x"]
        y = o["y"]
        scale = o["scale"]
        # rotation旋转先不写
        view = o["visible"]
        # 拖动不实现
        scene = o["scene"]
        # 去寻找这个角色的图片
        # 主图片
        current_style_id = o["current_style_id"]
        ini["screen"][o["scene"]][o["id"]] = {
            "name": o["name"],
            "type": "img",
            "view": view,
            "styles": {},
            "x": 0,
            "y": 0
        }
        for k in o["styles"]:
            if "cdn_url" in theatre["styles"][k]:
                source = theatre["styles"][k]["cdn_url"]
            else:
                save_base64_image(theatre["styles"][k]["url"], theatre["styles"][k]["id"])
            filename = download_file(source, './data/img')

            if k == current_style_id:
                w, h = getSize(filename)
                ini["screen"][o["scene"]][o["id"]]["source"] = filename
                ini["screen"][o["scene"]][o["id"]]["w"] = w * scale * 0.01
                ini["screen"][o["scene"]][o["id"]]["h"] = h * scale * 0.01
                ini["screen"][o["scene"]][o["id"]]["x"] = (size["width"] / 2) + (x - w * scale * 0.01 / 2)
                ini["screen"][o["scene"]][o["id"]]["y"] = (size["height"] / 2) - (y + h * scale * 0.01 / 2)
            else:
                ini["screen"][o["scene"]][o["id"]]["styles"][k] = filename

print(ini)
# 保存为json文件
with open('./data/ini.json', 'w', encoding='utf-8') as f:
    json.dump(ini, f, ensure_ascii=False, indent=4)
